import React, { useState } from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { CheckOutlined, CopyOutlined } from '@ant-design/icons';

import prettier from "prettier/standalone";

import "./styles.scss"

/**
 * 代码块组件 - 用于展示语法高亮的代码片段
 * @param {string} code - 需要展示的代码字符串
 * @param {string} language - 代码语言类型,用于语法高亮
 * @returns {JSX.Element} 返回一个带有语法高亮的代码块组件
 * 
 * @example
 * <CodeBlock 
 *   code="const hello = 'world'" 
 *   language="javascript" 
 * />
 */
const CodeBlock = ({ code, language }) => {
    const [copied, setCopied] = useState(false);

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(code);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            console.error('复制失败:', err);
        }
    };

    return (
        <>
            <div className="code-block-wrapper">
                <SyntaxHighlighter
                    language={language}
                    style={vscDarkPlus}
                    showLineNumbers
                    wrapLines
                    lineProps={{ style: { wordBreak: 'break-all', whiteSpace: 'pre-wrap' } }}
                    customStyle={{
                        borderRadius: '8px',
                        padding: '16px',
                        fontSize: '14px',
                        lineHeight: '1.5',
                        height: '100%',
                        // margin: '20px 20'
                    }}
                >
                    {code}
                </SyntaxHighlighter>
                <button
                    onClick={handleCopy}
                    className="copy-button"
                    aria-label="复制代码"
                >
                    {copied ? <CheckOutlined /> : <CopyOutlined />}
                </button>

                {copied && <div className="copy-tip">已复制!</div>}

            </div>


        </>
    );
};

export default CodeBlock;